import {
  Dimension,
  selectPmData,
  submitPm,
  temporarySavePm,
  DimensionTarget
} from '@/api/myPerformance'
import {CnBoldP, CnNormalP} from '@/components/text'
import {useRouteQuery} from '@/hooks/pageRedirect'
import useGroup from '@/hooks/pm/group'
import useMyPm from '@/hooks/pm/myPm'
import useOwner from '@/hooks/pm/owner'
import useProgress from '@/hooks/pm/progress'
import {useTableLoading} from '@/hooks/tableHook'
import PhoneLayout from '@/layout/index_phone'
import {SetTargetPageQuery, toMyPerformance, toPhoneMyPerformance} from '@/libs/pageRedirect'
import { defineComponent, reactive, onMounted } from 'vue'
import EditDimen from '../setTarget/components/EditDimen'

export default defineComponent({
  name: 'phone-setTargetByLeader',
  setup(props, ctx) {

    const {route, router, getQueryData} = useRouteQuery({
      queryKeys: ['pmId', 'progressId']
    })

    let pageQuery = getQueryData<SetTargetPageQuery>()
    if (!pageQuery) {
      router.back()
      return () => <div></div>
    }

    const {
      pmId: defaultPmId,
      groupId: defaultGroupId,
      progressId: defaultProgressId,
      userDDId: defaultUserDDId
    } = pageQuery

    const {startLoading, closeLoading, loading} = useTableLoading()

    const {getPmGroupById} = useGroup()

    const {udpateOwnerByPmId, owner, udpateOwner} = useOwner()

    const {getPmByPmId, checkTargetWeight, pm} = useMyPm()

    const {updatePmProgress, excludeUserBySelectAppointUser} = useProgress()

    let state = reactive<{
      /**维度tabs栏，当前维度的id */
      dimensTabsActiveKey: number
      /**当前绩效的维度列表 */
      pmDataList: MyPm.PmData[] | null
      pmGroupBaseInfo: Evaluation.EvalutaionData | undefined

      /**保存/暂存时 发送的维度数据 */
      dimensions: Dimension[]
    }>({
      dimensTabsActiveKey: -1,
      pmDataList: null,
      pmGroupBaseInfo: undefined,
      dimensions: []
    })

    /**获取页面数据 */
    function getPageData() {
      startLoading()
      /**获取个人绩效中的维度 */
      selectPmData({pmId: Number(defaultPmId)})
        .then(pmdataListRes => {
          if (pmdataListRes.data) pmdataListRes.data.sort((a, b) => a.sort - b.sort)
          state.pmDataList = pmdataListRes.data || []

          if (state.pmDataList && state.pmDataList.length) {
            console.log('个人绩效中有数据', pmdataListRes.data)
            state.dimensions = combSetTargetDimensionsByPmDatas(state.pmDataList)
            state.dimensTabsActiveKey = state.pmDataList[0].sort
            getPmByPmId({
              pmId: Number(defaultPmId),
              updatePm: true,
              success: data => {
                if (data.pmStageCode !== '0017') {
                  router.back()
                  return
                }
                udpateOwner({ownerDDId: data.pmUserDDId})
              }
            })
          } else {
            console.log('个人绩效中没有数据', pmdataListRes.data)
            // 如果没有默认考评组Id，先根据默认pmId查询考评组
            getPmByPmId({
              pmId: Number(defaultPmId),
              updatePm: true,
              success: data => {
                if (data.pmStageCode !== '0017') {
                  router.back()
                  return
                }
                getPmGroupById({
                  pmGroupId: data.pmGroupId,
                  success: getPmGroupByIdCallBack
                })
                udpateOwner({ownerDDId: data.pmUserDDId})
              }
            })
          }
          closeLoading()
        })
        .catch(err => {
          closeLoading()
        })
    }

    /**保存点击 */
    function handleSubmitClick() {
      let flag = checkTargetWeight(state.dimensions)
      if (!flag) return
      console.log('校验完毕')

      startLoading()
      submitPm({
        pmProgressId: defaultProgressId,
        data: state.dimensions
      })
        .then(res => {
          closeLoading()
          router.back()
        })
        .catch(err => {
          closeLoading()
          getPageData()
        })
    }

    /**暂存点击 */
    function handleTemporarySaveClick() {
      return
      startLoading()

      temporarySavePm({pmProgressId: defaultProgressId, data: state.dimensions})
        .then(res => {
          closeLoading()
          getPageData()
        })
        .catch(err => {
          closeLoading()
        })
    }

    function combPmDatasByPmGroupDimensions(
      data: Evaluation.PmGroupDimension[],
      pmGroup: Evaluation.EvalutaionData
    ): MyPm.PmData[] {
      return data.map<MyPm.PmData>(item => ({
        pmId: Number(defaultPmId),
        pmDimensionId: item.pmGroupDimensionId,
        pmDimensionName: item.pmGroupDimensionName,
        pmDimensionTypeCode: item.pmGroupDimensionTypeCode,
        pmDimensionWeight: item.pmGroupDimensionWeight,
        isCustomSelf: item.isCustomSelf,
        isImport: item.isImport,
        sort: item.sort,
        pmTargetList: item.pmGroupDimensionTargetList.map<MyPm.PmTarget>(dimensionTarget => ({
          isBonus: dimensionTarget.isBonus,
          pmTargetRange: dimensionTarget.pmGroupDimensionTargetRange,
          isMustSelect: dimensionTarget.isMustSelect,
          pmTargetId: dimensionTarget.pmGroupDimensionTargetId,
          pmDimensionId: dimensionTarget.pmGroupDimensionId,
          scoreSelfCheckList: null,
          leaderCheckList: null,
          appointCheckList: null,
          pmTargetName: dimensionTarget.pmGroupDimensionTargetName,
          pmTargetStand: dimensionTarget.pmGroupDimensionTargetStand,
          pmTargetWeight: dimensionTarget.pmGroupDimensionTargetWeight,
          sort: dimensionTarget.sort,
          appointScoreSign: pmGroup.appointScoreSwitch,
          appointUserDDId: '',
          makeProperty: undefined
        }))
      }))
    }

    function combSetTargetDimensionsByPmDatas(data: MyPm.PmData[]): Dimension[] {
      return data.map<Dimension>(pmData => {
        return {
          pmDimensionId: pmData.pmDimensionId,
          pmDimensionName: pmData.pmDimensionName,
          pmDimensionTypeCode: pmData.pmDimensionTypeCode,
          pmDimensionWeight: pmData.pmDimensionWeight,
          isCustomSelf: pmData.isCustomSelf,
          isImport: pmData.isImport,
          sort: pmData.sort,
          pmTargetList: pmData.pmTargetList.map<DimensionTarget>(target => {
            return {
              isBonus: target.isBonus,
              pmTargetRange: target.pmTargetRange,
              pmTargetId: target.pmTargetId,
              appointScoreSign: target.appointScoreSign,
              appointUserDDId: target.appointUserDDId,
              makeProperty: undefined,
              pmTargetName: target.pmTargetName,
              pmTargetStand: target.pmTargetStand,
              pmTargetWeight: target.pmTargetWeight,
              sort: target.sort,
              isMustSelect: target.isMustSelect || 0,
              pmDimensionId:target.pmDimensionId
            }
          })
        }
      })
    }

    function getPmGroupByIdCallBack(pmGroup: Evaluation.EvalutaionData) {
      pmGroup.pmGroupDimensionList.sort((a, b) => a.sort - b.sort)

      state.pmGroupBaseInfo = pmGroup

      state.pmDataList = combPmDatasByPmGroupDimensions(pmGroup.pmGroupDimensionList, pmGroup)

      state.dimensions = combSetTargetDimensionsByPmDatas(state.pmDataList)

      state.dimensTabsActiveKey = pmGroup.pmGroupDimensionList[0].sort

      console.log('个人绩效中没有指标数据，使用考评组中的默认指标', pmGroup, state.dimensions)

      closeLoading()
    }

    onMounted(() => {
      getPageData()
      updatePmProgress({pmId: defaultPmId})
    })

    return () => (
      <PhoneLayout>
        <div class='flex-1 flex flex-col overflow-hidden'>
          {/* 用户信息 */}
          <div class='w-full h-80 bg-white flex items-center gap-x-8 px-16'>
            <img src={owner.value?.avatar} class='w-40 h-40 rounded-4'></img>
            <div>
              <CnBoldP>{owner.value?.userName || ''}</CnBoldP>
              <CnNormalP>{owner.value?.deptName || ''}</CnNormalP>
              {pm.value ? <CnNormalP>{pm.value.pmFormName || ''}</CnNormalP> : null}
            </div>
          </div>

          {/* 绩效内容 */}
          <div class='flex-1 overflow-y-auto flex flex-col gap-y-12 pb-16'>
            {state.dimensions &&
              state.dimensions.map((dimen, idx) =>
                owner.value ? (
                  <EditDimen
                    sourceType='self'
                    hidden={false}
                    dimension={dimen}
                    pmId={Number(defaultPmId)}
                    groupId={Number(defaultGroupId)}
                    onDimensionChange={data => {
                      console.log('维度数据变化', data)

                      state.dimensions[idx] = data
                    }}
                    owner={owner.value}
                    showAppointScore={
                      state.pmGroupBaseInfo?.appointScoreSwitch === 1 ? true : false
                    }
                    excludeUserIds={excludeUserBySelectAppointUser.value}
                  ></EditDimen>
                ) : null
              )}
          </div>
          {/* 底部按钮 */}
          <div class='h-60 bg-white border-t-1 border-cardLine flex items-center justify-center z gap-x-12 px-16 overflow-x-auto'>
            <a-button type='primary' onClick={handleSubmitClick}>
              提交
            </a-button>
          </div>
        </div>
      </PhoneLayout>
    )
  }
})
